package cn.com.cifi.mars.web.aop;

import cn.com.cifi.mars.common.bean.R;
import cn.com.cifi.mars.common.exception.MsgException;
import cn.com.cifi.mars.constant.CodeEnum;
import cn.com.cifi.mars.util.json.JsonResultRespUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ConstraintViolationException;

/**
 * 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 */
@Slf4j
@ControllerAdvice
public class BaseControllerExceptionHandler {

    /**
     * 参数校验异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public R constraintViolationException(ConstraintViolationException e) {
        String msg = e.getConstraintViolations().stream().map(x -> x.getMessage()).reduce((x, y) -> x + "," + y).get();
        return JsonResultRespUtils.create(CodeEnum.ILLEGAL_REQUEST_PARAM_ERROR.getCode(), msg);
    }

    /**
     * 对象参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public R constraintViolationException(MethodArgumentNotValidException e) {
        String msg = e.getBindingResult().getAllErrors().stream().map(x -> x.getDefaultMessage())
                .reduce((x, y) -> x + "," + y).get();
        return JsonResultRespUtils.create(CodeEnum.ILLEGAL_REQUEST_PARAM_ERROR.getCode(), msg);
    }

    /**
     * 请求方法异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public R httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return JsonResultRespUtils.create(CodeEnum.ILLEGAL_REQUEST_METHOD_ERROR.getCode(), e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public R exception(Exception e) {
        log.error(null!=e?e.getMessage():"");
        return JsonResultRespUtils.internalError();
    }

    /**
     * 拦截业务异常
     */
    @ExceptionHandler(MsgException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public R msgException(MsgException e) {
        log.error(e.getMessage());
        return JsonResultRespUtils.create(e.getCode(), e.getMsg());
    }

}
